package com.tzu.ft.transfer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import com.tzu.ft.base.FTConfig;
import com.tzu.ft.transfer.client.Client;
import com.tzu.ft.transfer.client.FTClient;
import com.tzu.ft.transfer.client.FTSSLClient;
import com.tzu.ssl.KeyInfo;

public class ClientFactory {

	private static ThreadPoolExecutor threadPoolExecutor;

	private static KeyInfo keyInfo;

	private static boolean ssl = false;

	private static Map<String, Client> CLIENT_MAP = new HashMap<>();

	public static void init(boolean ssl) {
		ClientFactory.ssl = ssl;
		if (ssl) {
			keyInfo = FTConfig.getKeyInfo();
		}
		// 获取默认线程池配置
		int threads = FTConfig.getTaskThreadNum();
		// 线程池
		threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);

	}

	public static Client getClient(String host, int port, ClientUI ui) throws Exception {
		Client client = null;
		if (ssl) {
			client = new FTSSLClient();

			client.init(host, port, keyInfo, ui);
		} else {
			client = new FTClient();
			client.init(host, port, null, ui);
		}
		CLIENT_MAP.put(client.hashCode() + "", client);
		return client;
	}

	public static void addTask(ClientRunning running) throws Exception {
		// 如果超过并发数，则排队
		threadPoolExecutor.execute(running);
//
//        int active = threadPoolExecutor.getActiveCount();
//        if (active < FTConfig.getMaxThreads()) {
//            threadPoolExecutor.execute(running);
//        } else {
//            throw new Exception("并行队列已经到达最大值，任务添加失败");
//        }
	}

	/**
	 * 销毁
	 */
	public static void destory(ClientRunning running) {
		try {
			if (null != running) {
				Client client = running.getClient();
				CLIENT_MAP.remove(client.hashCode());
				client.exit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void destoryFactory() {
		List<String> keylist = new ArrayList<String>(CLIENT_MAP.keySet());
		for (String key : keylist) {
			try {
				Client client = CLIENT_MAP.get(key);
				client.exit();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		CLIENT_MAP.clear();
		if (null != threadPoolExecutor) {
			threadPoolExecutor.shutdown();
			threadPoolExecutor = null;
		}

	}

	public static Map<String, Client> getClientMap() {
		return CLIENT_MAP;
	}

	/** 获取显示任务数 */
	public static int getTaskActiveCount() {
//		if (null != threadPoolExecutor) {
//			int ac = threadPoolExecutor.getActiveCount();
//			ac -= 1;
//			return ac < 0 ? 0 : ac;
//		}
		return CLIENT_MAP.size();
	}

	/** 获取显示任务数 */
	public static int getTaskWaitCount() {
		if (null != threadPoolExecutor) {
			return threadPoolExecutor.getQueue().size();
		}
		return 0;
	}

}
